<template>
  <div class="page-container docker-manager">
    <div v-if="loading" class="loading-spinner">
      <el-progress type="circle" :percentage="100" status="success" :indeterminate="true" :duration="2" />
      <p>正在加载容器数据...</p>
    </div>

    <div v-else-if="error" class="error-message">
      <el-alert type="error" :title="'容器数据加载失败'" :description="error" show-icon :closable="false" />
    </div>

    <div v-else class="page-content">
      <div class="page-header">
        <h1><el-icon><Box /></el-icon> Docker 容器管理</h1>
        <div class="header-actions">
          <el-button @click="fetchContainers" :loading="refreshing" type="primary">
            <el-icon><Refresh /></el-icon>
            刷新状态
          </el-button>
        </div>
      </div>

      <!-- 智能镜像更新系统 - 主要功能区域 -->
      <div class="intelligent-update-section">
        <ImageUpdateContainer />
      </div>

      <!-- 当前运行容器展示区域 -->
      <div class="containers-section">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <h3><el-icon><Monitor /></el-icon> 当前运行的容器</h3>
              <span class="container-count">共 {{ containers.length }} 个容器</span>
            </div>
          </template>
        </el-card>
      </div>

      <!-- 容器展示网格 -->
      <div class="container-grid">
        <el-card v-for="container in containers" :key="container.id" class="container-card" shadow="hover"
          :class="`status-${container.status}`">
          <template #header>
            <div class="card-header">
              <div class="container-name">
                <el-icon :class="['status-icon', getStatusClass(container.status)]"><component :is="getIconForStatus(container.status)" /></el-icon>
                <span>{{ container.name }}</span>
              </div>
              <el-tag size="small" :type="getStatusType(container.status)">{{ container.status }}</el-tag>
            </div>
          </template>

          <div class="card-body">
            <div class="info-row">
              <el-icon><CollectionTag /></el-icon>
              <span>{{ container.image }}</span>
            </div>
            <div class="info-row short-id">
              <el-icon><Flag /></el-icon>
              <span>{{ container.short_id }}</span>
            </div>
            
            <div class="resource-usage">
              <div class="resource-item">
                <span>CPU</span>
                <el-progress :percentage="container.stats?.cpu_percent || 0" :color="cpuColors" :stroke-width="6" />
              </div>
              <div class="resource-item">
                <span>内存</span>
                <el-progress :percentage="container.stats?.mem_percent || 0" :color="memoryColors" :stroke-width="6" />
              </div>
            </div>

            <div class="ports-info">
              <el-icon><Guide /></el-icon>
              <div v-if="container.ports.length > 0" class="port-tags">
                 <el-tooltip v-for="p in container.ports" :key="p.host_port" :content="`主机端口 -> 容器端口`">
                   <el-tag type="info" size="small">{{ p.host_port }}:{{ p.container_port }}</el-tag>
                 </el-tooltip>
              </div>
              <span v-else class="no-ports">未映射端口</span>
            </div>
          </div>
          
          <div class="card-footer">
            <el-button-group>
               <el-tooltip content="查看日志"><el-button size="small" @click="showLogs(container)"><el-icon><Document /></el-icon></el-button></el-tooltip>
               <el-tooltip content="重启"><el-button size="small" @click="handleAction('restart', container)" :loading="actionLoading[container.id]"><el-icon><RefreshRight /></el-icon></el-button></el-tooltip>
            </el-button-group>
            <el-button-group>
              <el-button v-if="container.status !== 'running'" size="small" type="success" @click="handleAction('start', container)" :loading="actionLoading[container.id]">启动</el-button>
              <el-button v-if="container.status === 'running'" size="small" type="warning" @click="handleAction('stop', container)" :loading="actionLoading[container.id]">停止</el-button>
              <el-popconfirm title="确定删除这个容器吗？" @confirm="handleAction('remove', container)" width="220" confirm-button-text="确认删除">
                 <template #reference><el-button size="small" type="danger" :loading="actionLoading[container.id]">删除</el-button></template>
              </el-popconfirm>
            </el-button-group>
          </div>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="logDialog.visible" :title="`'${logDialog.containerName}' 的日志`" width="70%" top="10vh">
      <pre class="log-content" v-loading="logDialog.loading">{{ logDialog.logs }}</pre>
      <template #footer>
        <el-button @click="logDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 配置管理对话框 -->
    <el-dialog v-model="showConfigDialog" title="镜像配置管理" width="70%" top="10vh">
      <div class="config-management">
        <!-- 添加新镜像配置 -->
        <el-card class="add-config-card" shadow="never">
          <template #header>
            <h4>添加镜像配置</h4>
          </template>
          <el-form :model="newImageConfig" label-width="120px" size="small">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="镜像名称" required>
                  <el-input v-model="newImageConfig.name" placeholder="例如: mobox-docker/backend" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="镜像仓库" required>
                  <el-input v-model="newImageConfig.registry" 
                           placeholder="例如: crpi-axr6nxua9k92sqiz.cn-hangzhou.personal.cr.aliyuncs.com" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="当前版本">
                  <el-input v-model="newImageConfig.current_version" placeholder="latest" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="描述">
                  <el-input v-model="newImageConfig.description" placeholder="镜像说明" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="自动更新">
                  <el-switch v-model="newImageConfig.auto_update" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="启用监控">
                  <el-switch v-model="newImageConfig.enabled" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button @click="addImageConfig" type="primary" :loading="addingConfig">
                <el-icon><Plus /></el-icon>
                添加配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 现有配置列表 -->
        <el-card class="config-list-card" shadow="never">
          <template #header>
            <h4>现有配置</h4>
          </template>
          <el-table :data="imageConfigs" style="width: 100%">
            <el-table-column prop="name" label="镜像名称" />
            <el-table-column prop="registry" label="仓库地址" show-overflow-tooltip />
            <el-table-column prop="current_version" label="当前版本" width="120" />
            <el-table-column label="自动更新" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.auto_update ? 'success' : 'info'" size="small">
                  {{ scope.row.auto_update ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.enabled ? 'success' : 'danger'" size="small">
                  {{ scope.row.enabled ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-popconfirm 
                  title="确定删除这个配置吗？" 
                  @confirm="removeImageConfig(scope.row.name)"
                  width="200"
                >
                  <template #reference>
                    <el-button type="danger" size="small" text>删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 远程配置URL -->
        <el-card class="remote-config-card" shadow="never">
          <template #header>
            <h4>远程配置</h4>
          </template>
          <el-form label-width="120px" size="small">
            <el-form-item label="配置URL">
              <el-input 
                v-model="remoteConfigUrl" 
                placeholder="远程镜像配置文件URL"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="saveRemoteConfig" type="primary" :loading="savingConfig">
                保存配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="showConfigDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';
import { CollectionTag, Flag, Guide, Document, RefreshRight, CircleCheck, CircleClose, VideoPause, Refresh, Box, Monitor } from '@element-plus/icons-vue';
import api from '@/services/api';
import { formatBytes } from '@/utils/formatters';
import { io } from 'socket.io-client';
import ImageUpdateContainer from '@/components/ImageUpdateContainer.vue';

// 容器管理状态
const loading = ref(true);
const refreshing = ref(false);
const error = ref(null);
const containers = ref([]);
const actionLoading = reactive({});

const logDialog = reactive({
  visible: false,
  loading: false,
  logs: '',
  containerName: ''
});

// 颜色配置
const cpuColors = [
  { color: '#67C23A', percentage: 60 },
  { color: '#E6A23C', percentage: 80 },
  { color: '#F56C6C', percentage: 100 },
];
const memoryColors = [
  { color: '#409EFF', percentage: 60 },
  { color: '#E6A23C', percentage: 80 },
  { color: '#F56C6C', percentage: 100 },
];

// 生命周期钩子
onMounted(() => {
  fetchContainers();
});

// 容器管理函数
const fetchContainers = async () => {
  if (refreshing.value) return;
  refreshing.value = true;
  error.value = null;
  
  try {
    const response = await api.getDockerContainers();
    containers.value = response.data.containers.sort((a, b) => a.name.localeCompare(b.name));
  } catch (err) {
    error.value = `无法从后端服务获取容器数据。错误: ${err.message}`;
    ElMessage.error('获取容器列表失败！');
    console.error(err);
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

const getStatusType = (status) => {
  if (status === 'running') return 'success';
  if (status.includes('exit')) return 'danger';
  return 'info';
};

const getStatusClass = (status) => {
  if (status === 'running') return 'status-running';
  if (status.includes('exit')) return 'status-exited';
  return 'status-stopped';
}

const getIconForStatus = (status) => {
    if (status === 'running') return CircleCheck;
    if (status.includes('exit')) return CircleClose;
    return VideoPause;
}

const handleAction = async (action, container) => {
  actionLoading[container.id] = true;
  const actionMap = {
    start: { func: api.startContainer, verb: '启动' },
    stop: { func: api.stopContainer, verb: '停止' },
    restart: { func: api.restartContainer, verb: '重启' },
    remove: { func: api.removeContainer, verb: '删除' },
  };

  try {
    await actionMap[action].func(container.id);
    ElNotification({
      title: '操作成功',
      message: `容器 ${container.name} 已${actionMap[action].verb}。`,
      type: 'success',
    });
    setTimeout(fetchContainers, 1000);
  } catch (err) {
    ElNotification({
      title: '操作失败',
      message: `无法${actionMap[action].verb}容器 ${container.name}。错误: ${err.response?.data?.error || err.message}`,
      type: 'error',
    });
  } finally {
    actionLoading[container.id] = false;
  }
};

const showLogs = async (container) => {
  logDialog.visible = true;
  logDialog.loading = true;
  logDialog.containerName = container.name;
  logDialog.logs = '正在加载日志...';

  try {
    const response = await api.getContainerLogs(container.id);
    logDialog.logs = response.data.logs || '该容器没有输出日志。';
  } catch(err) {
    logDialog.logs = `加载日志失败: ${err.response?.data?.error || err.message}`;
    ElMessage.error('获取容器日志失败！');
  } finally {
    logDialog.loading = false;
  }
};

function formatTime(timestamp) {
  if (!timestamp) return '从未';
  const date = new Date(timestamp * 1000);
  return date.toLocaleString('zh-CN');
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.loading-spinner, .error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
}

.loading-spinner p {
  margin-top: 20px;
  color: #666;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 智能镜像更新区域样式 */
.intelligent-update-section {
  margin-bottom: 20px;
}

/* 容器展示区域样式 */
.containers-section {
  margin-bottom: 20px;
}

.containers-section .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.containers-section .card-header h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.container-count {
  color: #666;
  font-size: 14px;
}

/* 容器卡片样式 */
.container-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.container-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.container-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.container-card.status-running {
  border-left: 4px solid #67C23A;
}

.container-card.status-exited {
  border-left: 4px solid #F56C6C;
}

.container-card.status-stopped {
  border-left: 4px solid #909399;
}

.container-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #2c3e50;
}

.status-icon.status-running {
  color: #67C23A;
}

.status-icon.status-exited {
  color: #F56C6C;
}

.status-icon.status-stopped {
  color: #909399;
}

.card-body {
  padding: 0;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f2f5;
  font-size: 14px;
}

.info-row:last-child {
  border-bottom: none;
}

.short-id {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #666;
}

.resource-usage {
  margin: 15px 0;
}

.resource-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.resource-item span {
  font-size: 12px;
  font-weight: 500;
  color: #666;
  min-width: 40px;
}

.resource-item .el-progress {
  flex: 1;
  margin-left: 15px;
}

.ports-info {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-top: 10px;
}

.port-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.no-ports {
  font-size: 12px;
  color: #999;
  font-style: italic;
}

.card-footer {
  padding-top: 15px;
  border-top: 1px solid #f0f2f5;
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

/* 日志对话框样式 */
.log-content {
  background: #1e1e1e;
  color: #d4d4d4;
  padding: 15px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
}
</style> 